package com.valuegroup.smarttodo.ui.todo.task.qucikadd;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.valuegroup.smarttodo.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mehdi.sakout.fancybuttons.FancyButton;

/**
 * 浮动在键盘上的快捷输入框
 */
public class QucikAddActivity extends Activity implements View.OnClickListener {
    public static final String KEY_EDITOR_HOLDER = "editor_holder";
    public static final String KEY_EDITOR_CHECKER = "editor_checker";
    public static final String KEY_REPEAT_TO_ADD = "repeat_to_add";
    public static final String KEY_WINDOW_GRAVITY = "window_gravity";
    public static final String KEY_IS_FINISH = "key_is_finish";
    private View cancel;
    private View submit;
    private View submitNoContent;
    private QucikAddEditText etContent;
    private static QuickAddEditorCallback mEditorCallback;
    private static ExpansionCallback mExpansionCallback;
    private QuickAddHolder holder;
    private QucikAddInputCheckRule checkRule;
    private FancyButton btnFinish;
    private boolean isFinish = false;
    private boolean isClicked = false;
    // 支持重复添加
    private boolean repeatToAdd;
    // 主窗口布局方向
    private int windowGravity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        holder = (QuickAddHolder) getIntent().getSerializableExtra(KEY_EDITOR_HOLDER);
        checkRule = (QucikAddInputCheckRule) getIntent().getSerializableExtra(KEY_EDITOR_CHECKER);
        repeatToAdd = getIntent().getBooleanExtra(KEY_REPEAT_TO_ADD, true);
        isFinish = getIntent().getBooleanExtra(KEY_IS_FINISH, false);
        windowGravity = getIntent().getIntExtra(KEY_WINDOW_GRAVITY, Gravity.BOTTOM);
        if (holder == null) {
            throw new RuntimeException("QuickAddHolder params not found!");
        }
        setContentView(holder.layoutResId);
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        getWindow().setGravity(windowGravity);
        if (mEditorCallback != null) {
            mEditorCallback.onAttached((ViewGroup) getWindow().getDecorView());
        }

        initView();
        setEvent();

        /**
         * 动态给EditText获得焦点并弹起软键盘
         */
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        etContent.setFocusable(true);
        etContent.setFocusableInTouchMode(true);
        etContent.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(etContent, 0);
    }


    private void initView() {
        cancel = findViewById(holder.cancelViewId);
        submit = findViewById(holder.submitViewId);
        submitNoContent = findViewById(holder.noContentBtn);
        etContent = findViewById(holder.editTextId);
        if (holder.finishBtnId != 0) {
            btnFinish = findViewById(holder.finishBtnId);
            if (btnFinish != null) {
                btnFinish.setBackgroundColor(ContextCompat.getColor(this, isFinish ? R.color.btnFinishFocus : R.color.btnFinishDefault));
            }
        }

        if (holder.hintStrId != 0) {
            etContent.setHint(holder.hintStrId);
        }
    }

    private void setEvent() {
        if (cancel != null)
            cancel.setOnClickListener(this);
        if (btnFinish != null)
            btnFinish.setOnClickListener(this);

        submit.setOnClickListener(this);

        submitNoContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        etContent.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    submitNoContent.setVisibility(View.VISIBLE);
                    submit.setVisibility(View.GONE);
                } else {
                    submitNoContent.setVisibility(View.GONE);
                    submit.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public static void openEditor(Context context, QuickAddEditorCallback editorCallback, QuickAddHolder holder) {
        openEditor(context, editorCallback, holder, null);
    }

    public static void openEditor(Context context, QuickAddEditorCallback editorCallback, QuickAddHolder holder, QucikAddInputCheckRule checkRule) {
        Intent intent = new Intent(context, QucikAddActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(KEY_EDITOR_HOLDER, holder);
        intent.putExtra(KEY_EDITOR_CHECKER, checkRule);
        intent.putExtra(KEY_REPEAT_TO_ADD, true);
        mEditorCallback = editorCallback;
        context.startActivity(intent);
    }

    public static void openEditorNoRepeat(Context context, QuickAddEditorCallback editorCallback, QuickAddHolder holder, QucikAddInputCheckRule checkRule) {
        Intent intent = new Intent(context, QucikAddActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(KEY_EDITOR_HOLDER, holder);
        intent.putExtra(KEY_EDITOR_CHECKER, checkRule);
        intent.putExtra(KEY_REPEAT_TO_ADD, false);
        mEditorCallback = editorCallback;
        context.startActivity(intent);
    }

    public static void openEditorNoRepeatAndSetFinish(Context context, QuickAddEditorCallback editorCallback, QuickAddHolder holder, QucikAddInputCheckRule checkRule, boolean isFinish, ExpansionCallback expansionCallback) {
        Intent intent = new Intent(context, QucikAddActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(KEY_EDITOR_HOLDER, holder);
        intent.putExtra(KEY_EDITOR_CHECKER, checkRule);
        intent.putExtra(KEY_REPEAT_TO_ADD, false);
        intent.putExtra(KEY_IS_FINISH, isFinish);
        mEditorCallback = editorCallback;
        mExpansionCallback = expansionCallback;
        context.startActivity(intent);
    }

    public static void openEditorNoRepeat(Context context, QuickAddEditorCallback editorCallback, QuickAddHolder holder, QucikAddInputCheckRule checkRule, int windowGravity) {
        Intent intent = new Intent(context, QucikAddActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(KEY_EDITOR_HOLDER, holder);
        intent.putExtra(KEY_EDITOR_CHECKER, checkRule);
        intent.putExtra(KEY_REPEAT_TO_ADD, false);
        intent.putExtra(KEY_WINDOW_GRAVITY, windowGravity);
        mEditorCallback = editorCallback;
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == holder.cancelViewId) {
            isClicked = true;
            mEditorCallback.onCancel();
            finish();
        } else if (id == holder.submitViewId) {
            if (checkRule != null && !(checkRule.minLength == 0 && checkRule.maxLength == 0)) {
                if (!illegal()) {
                    mEditorCallback.onSubmit(etContent.getText().toString());
                    etContent.setText("");
                    // 提交后可以重复提交
                    if (!repeatToAdd) {
                        finish();
                    }
                }
                return;
            }
            mEditorCallback.onSubmit(etContent.getText().toString());
            // 清空内容
            etContent.setText("");
            if (!repeatToAdd) {
                finish();
            }
        } else if (id == R.id.btnFinish) {
            if (mExpansionCallback != null) {
                mExpansionCallback.onFinish(QucikAddActivity.this, !isFinish, new ChangeViewCallback() {
                    @Override
                    public void onChangeView(boolean change) {
                        updateFinishBtn(!isFinish);
                    }
                });
            }
        }
    }

    public void updateFinishBtn(boolean finish) {
        if (finish) {
            this.isFinish = true;
            btnFinish.setBackgroundColor(ContextCompat.getColor(this, R.color.btnFinishFocus));
        } else {
            this.isFinish = false;
            btnFinish.setBackgroundColor(ContextCompat.getColor(this, R.color.btnFinishDefault));
        }
    }


    private boolean illegal() {
        String content = etContent.getText().toString();
        if (TextUtils.isEmpty(content) || content.length() < checkRule.minLength) {
            Toast.makeText(this, getString(R.string.quickly_add_limit_min_warn, checkRule.minLength), Toast.LENGTH_SHORT).show();
            return true;
        }

        if (content.length() > checkRule.maxLength) {
            Toast.makeText(this, getString(R.string.quickly_add_limit_max_warn, checkRule.maxLength), Toast.LENGTH_SHORT).show();
            return true;
        }

        if (!TextUtils.isEmpty(checkRule.regxRule)) {
            Pattern pattern = Pattern.compile(checkRule.regxRule);
            Matcher matcher = pattern.matcher(content);
            if (!matcher.matches()) {
                Toast.makeText(this, getString(checkRule.regxWarn), Toast.LENGTH_SHORT).show();
                return true;
            }
        }

        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!isClicked && mEditorCallback != null) {
            mEditorCallback.onCancel();
        }
        mEditorCallback = null;
    }
}
